package com.lori.search.dao.imp;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.lori.search.dao.SolrDao;
import com.lori.search.pojo.Item;
import com.lori.search.pojo.SolrResult;
@Repository
public class SolrDaoimp implements SolrDao{
	//注入solrserver
	@Autowired
	private SolrServer httpSolrServer;

	@Override
	public SolrResult search(SolrQuery query) throws Exception {
		//创建返回结果对象
		SolrResult result = new SolrResult();
		//获得查询结果索引库、
		QueryResponse response = httpSolrServer.query(query);
		//获得商品列表
		SolrDocumentList documentList = response.getResults();
		//获得总记录数
		int total = (int) documentList.getNumFound();
		result.setTotal(total);
		//创建存放商品列表的集合
		List<Item> itemList = new ArrayList<Item>();
		//设置高亮
		Map<String, Map<String, List<String>>> highlighting = response.getHighlighting();
		//遍历商品列表，将数据存入集合中
		for(SolrDocument solrDocument:documentList){
			//创建pojo对象
			Item item = new Item();
			//将值赋给pojo对象
			item.setId((String) solrDocument.get("id"));
			item.setCatname((String) solrDocument.get("item_category_name"));
			item.setImage((String) solrDocument.get("item_image"));
			item.setItem_desc((String) solrDocument.get("item_desc"));
			item.setPrice((Long) solrDocument.get("item_price"));
			item.setSell_point((String) solrDocument.get("item_sell_point"));
			//取高亮
			Map<String, List<String>> map = highlighting.get("id");
			List<String> list = null;
			if(map != null){
				list = map.get("item_title");
			}
			//判断是否存在
			if(list != null && list.size() >0){
				item.setTitle(list.get(0));
			}else{
				item.setTitle((String) solrDocument.get("item_title"));
			}
			//将pojo对象存入集合中
			itemList.add(item);
		}
		//把集合存入solrresult
		result.setItemList(itemList);
		return result;
	}
	
}
